<?php
/**
 * The Validator class
 */
class Validator
{
	static private function _ban($value, $ruleValue)
	{
		return !preg_match($ruleValue, $value);
	}

	static private function _mask($value, $ruleValue)
	{
		return preg_match($ruleValue, $value);
	}

	static private function _equal_to($value, $ruleValue)
	{
		return $value === $ruleValue;
	}

	static private function _max_length($value, $ruleValue)
	{
		return mb_strlen($value) <= $ruleValue;
	}

	static private function _min_length($value, $ruleValue)
	{
		return mb_strlen($value) >= $ruleValue;
	}

	static private function _max_value($value, $ruleValue)
	{
		return $value <= $ruleValue;
	}

	static private function _min_value($value, $ruleValue)
	{
		return $value >= $ruleValue;
	}

	static private function _min_selected($value, $ruleValue)
	{
		return count($value) >= $ruleValue;
	}

	static private function _max_selected($value, $ruleValue)
	{
		return count($value) <= $ruleValue;
	}

	static private function _required($value, $ruleValue)
	{
		if (false == $ruleValue)
		{
			return true;
		}
		else
		{
			return is_array($value) && count($value) || strlen($value);
		}
	}

	/**
	 * Validate an element
	 * 
	 * @param array $element 
	 * @return array 
	 */
	static private function _validateElement($element)
	{
		$errorMessages = array();
		$label = $element['dtd']['label'];
		$value = $element['value'];

		if (is_array($element['dtd']['rules']) && count($element['dtd']['rules']))
		{
			$rules = $element['dtd']['rules'];
			$explain = isset($element['dtd']['explain']) ? $element['dtd']['explain'] : array();
			foreach ($rules as $key => $val)
			{
				$validateFunction = '_' . $key;
				if ((is_bool($rules[$key]) || 0 < strlen($rules[$key])) && !self::$validateFunction($value, $rules[$key]))
				{
					$errorMessages[$key] = sprintf((isset($explain[$key]) && strlen($explain[$key]) ? $explain[$key] : Config::$app['validator']['error_explain'][$key]), $label, $rules[$key]);
				}
			}
		}
		return $errorMessages;
	}

	/**
	 * Validate the data from client
	 * 
	 * @param array $args 
	 * @return array 
	 */
	static public function validate($validateCondition)
	{
		$errorMessages = array();
		foreach ($validateCondition as $key => $element)
		{
			$result = self::_validateElement($element);
			if (count($result))
			{
				$errorMessages[$key] = $result;
			}
		}
		return $errorMessages;
	}
}
